//截取位数
export const TimeDigit = (value, n, m) => {
	if(!value) return;
	return value.substring(n, m);
}

//取N位小数
export const Decimal = (value, n=2) => {
	if(!value) return 0;
	var m = Math.pow(10, n);
	if (value.toString().indexOf('-') != -1) {
		return Math.ceil(value * m) / m;
	} else {
		return Math.floor(value * m) / m;
	}
}

//过滤手机号码
export const MobileFilter = (value) => {
	return value.substr(0, 3) + '****' + value.substr(7, 4);
}

// 空值过滤
export const filNull = (value) => {
	if (value === 0) return 0
	if (!value) return '--'
	return value
}

// 空值过滤-数字
export const filNum = (value) => {
	if (!value) return 0
	return value
}

//将数值转化为亿并保留两位小数
export const numberFormat = (value, rate) => {
	if(!value) return 0
	let param = {};
	let k = 10000,
		i;
	if (value < k) {
		param.value = value
	} else {
		i = Math.floor(Math.log(value) / Math.log(k));
		if (i > 2) i = 2;
		param.value = ((value / Math.pow(k, i))).toFixed(2);
	}
	return Number(param.value);
}

//将数值转化为亿
export const numberFormatCompany = (value, rate) => {
	let param = {};
	let k = 10000,
		sizes = ['', '万', '亿'],
		i;
	if (value < k) {
		param.unit = ''
	} else {
		i = Math.floor(Math.log(value) / Math.log(k));
		if (i > 2) i = 2;
		param.unit = sizes[i];
	}
	return param.unit;
}

//格式化时间 fmt = 'yyyy-MM-dd hh:mm' 返回对应格式时间
export const timer = (value, fmt) => {
	if(!value) return;
	let newTime = new Date(value.replace(/-/g, '/'))
	if(!fmt){
		fmt = 'yyyy-MM-dd hh:mm';
	}
	if(/(y+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, (newTime.getFullYear() + '').substr(4 - RegExp.$1.length));
	}
	let o = {
		'M+': newTime.getMonth() + 1,
		'd+': newTime.getDate(),
		'h+': newTime.getHours(),
		'm+': newTime.getMinutes(),
		's+': newTime.getSeconds()
	};
	
	function padLeftZero(str) {
	  return ('00'+str).substr(str.length);
	}

	// 遍历这个对象
	for (let k in o) {
		if (new RegExp(`(${k})`).test(fmt)) {
			// console.log(`${k}`)
			let str = o[k] + '';
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
		}
	}
	return fmt;
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export const formatTime = (time, option)=> {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}
